package com.powernode.map.service.impl;


import com.powernode.common.constant.RedisConstant;
import com.powernode.common.constant.SystemConstant;
import com.powernode.common.util.LocationUtil;
import com.powernode.driver.client.DriverInfoFeignClient;
import com.powernode.map.repository.OrderServiceLocationRepository;
import com.powernode.map.service.LocationService;
import com.powernode.model.entity.driver.DriverSet;
import com.powernode.model.entity.map.OrderServiceLocation;
import com.powernode.model.form.map.OrderServiceLocationForm;
import com.powernode.model.form.map.SearchNearByDriverForm;
import com.powernode.model.form.map.UpdateDriverLocationForm;
import com.powernode.model.form.map.UpdateOrderLocationForm;
import com.powernode.model.vo.map.NearByDriverVo;

import com.powernode.model.vo.map.OrderLocationVo;
import com.powernode.model.vo.map.OrderServiceLastLocationVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LocationServiceImpl implements LocationService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private DriverInfoFeignClient driverInfoFeignClient;

    @Resource
    private OrderServiceLocationRepository orderServiceLocationRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 更新配送员位置信息
     * 将配送员的位置信息存入redis geo中
     */
    @Override
    public Boolean updateDriverLocation(UpdateDriverLocationForm updateDriverLocationForm) {
        //创建坐标点
        Point point = new Point(updateDriverLocationForm.getLongitude().doubleValue(),
                updateDriverLocationForm.getLatitude().doubleValue());

        //将顾客的坐标点存入redis 的geo中
        redisTemplate.opsForGeo().add(RedisConstant.DRIVER_GEO_LOCATION, point, updateDriverLocationForm.getDriverId().toString());

        return true;
    }

    /**
     * 删除配送员的位置信息(配送员下班了)
     */
    @Override
    public Boolean removeDriverLocation(Long driverId) {
        redisTemplate.opsForGeo().remove(RedisConstant.DRIVER_GEO_LOCATION, driverId.toString());

        return true;
    }

    /**
     * 搜索附近符合条件的配送员
     */
    @Override
    public List<NearByDriverVo> searchNearByDriver(SearchNearByDriverForm searchNearByDriverForm) {

        //定义中心点  订单起始位置
        Point point = new Point(searchNearByDriverForm.getLongitude().doubleValue(), searchNearByDriverForm.getLatitude().doubleValue());

        //定义半径  搜索附近5公里范围之内的配送员
        Distance distance = new Distance(SystemConstant.NEARBY_DRIVER_RADIUS, RedisGeoCommands.DistanceUnit.KILOMETERS);

        //以point为中心，distance为半径 搜索范围
        Circle circle = new Circle(point, distance);

        //定义GEO查询参数
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands
                .GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()  //包含距离
                .includeCoordinates() //包含坐标
                .sortAscending();//排序 升序

        //搜索范围内的配送员
        GeoResults<RedisGeoCommands.GeoLocation<String>> result = redisTemplate.opsForGeo().radius(RedisConstant.DRIVER_GEO_LOCATION, circle, geoRadiusCommandArgs);

        //获取集合数据(包含配送员的信息)
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = result.getContent();

        //构建返回集合对象 符合条件的配送员数据
        List<NearByDriverVo> list = new ArrayList<>();

        if (!CollectionUtils.isEmpty(content)) {
            Iterator<GeoResult<RedisGeoCommands.GeoLocation<String>>> iterator = content.iterator();

            while (iterator.hasNext()) {
                //获取集合中的数据
                GeoResult<RedisGeoCommands.GeoLocation<String>> item = iterator.next();

                //获取配送员的id
                Long driverId = Long.parseLong(item.getContent().getName());

                //当前的距离  保留2位小数
                BigDecimal currentDistance = new BigDecimal(item.getDistance().getValue()).setScale(2, RoundingMode.HALF_UP);

                //获取配送员的个性化配置
                DriverSet driverSet = driverInfoFeignClient.getDriverSet(driverId).getData();

                //判断配送员当前位置距离订单起始位置是否满足设置  AcceptDistance != 0 表示有设置
                if (driverSet.getAcceptDistance().doubleValue() != 0 && driverSet.getAcceptDistance().subtract(currentDistance).doubleValue() < 0) {
                    continue;
                }

                //判断总里程是否满足设置
                if (driverSet.getOrderDistance().doubleValue() != 0 && driverSet.getOrderDistance().subtract(searchNearByDriverForm.getMileageDistance()).doubleValue() < 0) {
                    continue;
                }

                //当前订单符合配送员的个性化设置
                NearByDriverVo nearByDriverVo = new NearByDriverVo();
                nearByDriverVo.setDriverId(driverId);
                nearByDriverVo.setDistance(currentDistance);

                list.add(nearByDriverVo);
            }
        }

        return list;
    }


    /**
     * 配送员赶往顾客起始位置  上传配送员的位置信息
     */
    @Override
    public Boolean updateDriverLocationToCache(UpdateOrderLocationForm updateOrderLocationForm) {
        OrderLocationVo orderLocationVo = new OrderLocationVo();
        orderLocationVo.setLatitude(updateOrderLocationForm.getLatitude());
        orderLocationVo.setLongitude(updateOrderLocationForm.getLongitude());
        //存入redis中
        //key 订单编号  value 配送员位置信息
        redisTemplate.opsForValue().set(RedisConstant.UPDATE_ORDER_LOCATION + updateOrderLocationForm.getOrderId(), orderLocationVo);

        return true;
    }

    /**
     * 配送员赶往顾客起始位置，查询配送员在redis中的存储的位置信息
     */
    @Override
    public OrderLocationVo getCacheOrderLocation(Long orderId) {
        OrderLocationVo orderLocationVo = (OrderLocationVo) redisTemplate.opsForValue()
                .get(RedisConstant.UPDATE_ORDER_LOCATION + orderId);

        return orderLocationVo;
    }

    /**
     * 上传配送员实际配送的位置信息
     */
    @Override
    public Boolean saveOrderServiceLocation(List<OrderServiceLocationForm> orderServiceLocationForms) {

        List<OrderServiceLocation> list = new ArrayList<>();

        orderServiceLocationForms.forEach(item -> {
            OrderServiceLocation orderServiceLocation = new OrderServiceLocation();
            BeanUtils.copyProperties(item, orderServiceLocation);
            //主键
            orderServiceLocation.setId(ObjectId.get().toString());
            orderServiceLocation.setCreateTime(new Date());
            list.add(orderServiceLocation);
        });

        //将list数据添加到mongoDB中
        orderServiceLocationRepository.saveAll(list);
        return true;
    }

    /**
     * 获取配送员最后的位置信息
     */
    @Override
    public OrderServiceLastLocationVo getOrderServiceLastLocation(Long orderId) {
        //从mongodb中查询创建时间最大的数据
        Query query = new Query();
        query.addCriteria(Criteria.where("orderId").is(orderId));//订单编号
        query.with(Sort.by(Sort.Order.desc("createTime")));//时间倒序
        query.limit(1);

        OrderServiceLocation orderServiceLocation = mongoTemplate.findOne(query, OrderServiceLocation.class);

        OrderServiceLastLocationVo orderServiceLastLocationVo = new OrderServiceLastLocationVo();
        if (orderServiceLocation != null) {

            BeanUtils.copyProperties(orderServiceLocation, orderServiceLastLocationVo);
        }

        return orderServiceLastLocationVo;
    }


    /**
     * 计算配送员的实际配送员距离
     */
    @Override
    public BigDecimal calculateOrderRealDistance(Long orderId) {
        //从mongodb中查询该订单配送员的配送位置信息
        List<OrderServiceLocation> orderServiceLocationList = orderServiceLocationRepository.findByOrderIdOrderByCreateTimeAsc(orderId);


        double realDistance = 0;//实际配送距离
        //循环遍历获取坐标点
        if (!CollectionUtils.isEmpty(orderServiceLocationList)) {
            for (int i = 0, size = orderServiceLocationList.size() - 1; i < size; i++) {
                OrderServiceLocation location1 = orderServiceLocationList.get(i);
                OrderServiceLocation location2 = orderServiceLocationList.get(i + 1);

                //计算2个坐标之间的距离
                double distance = LocationUtil.getDistance(location1.getLatitude().doubleValue(), location1.getLongitude().doubleValue(),
                        location2.getLatitude().doubleValue(), location2.getLongitude().doubleValue());

                realDistance += distance;
            }
        }

        //我们测试中，配送员没有移动 所以这里固定设置一个里程
        if (realDistance == 0) {
            return new BigDecimal(5);
        }

        return new BigDecimal(realDistance);

    }

}
